package com.xydtech.ecard.ecard.controller;

import com.xydtech.common.config.UrlConfig;
import com.xydtech.common.config.XydtechBusiPlatConfig;
import com.xydtech.common.core.domain.entity.SysDept;
import com.xydtech.common.enums.ApiContant;
import com.xydtech.common.enums.ResultStatus;
import com.xydtech.common.exception.ApiException;
import com.xydtech.common.model.ResponseModel;
import com.xydtech.common.token.WechatTokenUtil;
import com.xydtech.common.utils.file.FileUploadUtils;
import com.xydtech.common.utils.file.MimeTypeUtils;
import com.xydtech.common.wechat.domin.GetWechatQRCodeResponse;
import com.xydtech.common.wechat.util.WeChatQrCodeUtil;
import com.xydtech.ecard.config.domain.*;
import com.xydtech.ecard.config.service.IEcardPosterConfigureService;
import com.xydtech.ecard.config.service.IEcardPosterMakeListService;
import com.xydtech.ecard.config.service.IEcardPosterShareConfService;
import com.xydtech.ecard.config.service.IEcardPosterShareListService;
import com.xydtech.ecard.user.domain.EcardApiUserInfo;
import com.xydtech.ecard.user.service.IEcardApiUserService;
import com.xydtech.system.domain.SysWechatApplet;
import com.xydtech.system.service.ISysDeptService;
import com.xydtech.system.service.ISysWechatAppletService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Base64;
import java.util.List;

/**
 * 电子名片-海报模块接口Controller
 *
 * @author yjs
 * @date 2022/12/6 10:23
 */
@Controller
@Api(tags = "电子名片-海报模块")
@RequestMapping("/ecardSaasApi/poster")
public class EcardApiPosterController extends EcardApiBaseController {
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IEcardApiUserService ecardApiUserService;
    @Autowired
    private IEcardPosterMakeListService ecardPosterMakeListService;
    @Autowired
    private IEcardPosterConfigureService ecardPosterConfigureService;
    @Autowired
    private IEcardPosterShareListService ecardPosterShareListService;
    @Autowired
    private IEcardPosterShareConfService ecardPosterShareConfService;
    @Autowired
    private ISysWechatAppletService sysWeChatAppletService;
    @Autowired
    private UrlConfig urlConfig;
    //文件分布式存储开关
    @Value("${busiplat.minioUpload}")
    private boolean minioUpload;
    /**
     * 三方数据接口
     */
    @Value("${url.apiServiceUrl}")
    private String apiServiceUrl;

    /**
     * 查询机构下海报列表,根据登陆用户法人机构ID查询
     *
     * @author yjs
     * @date 2022/12/6 10:28
     */
    @GetMapping("/getOrganPosterList")
    @ApiOperation(value = "电子名片-海报-获取机构下海报列表", notes = "电子名片-海报-获取机构下海报列表")
    @ApiResponses({@ApiResponse(code = 0, message = "OK", response = EcardNewsConfig.class)})
    @ResponseBody
    public ResponseModel getOrganPosterList(@RequestParam(required = false) String posterType) {
        String salt = getSalt();//盐值
        //获取当前用户的信息
        EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
        //法人机构信息
        SysDept secondLevelDept = deptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
        //获取法人机构的ID
        Long legalManDeptId = secondLevelDept.getDeptId();
        EcardPosterConfigure ecardPosterConfigure = new EcardPosterConfigure();
        ecardPosterConfigure.setDeptId(legalManDeptId);
        ecardPosterConfigure.setSts("1");
        ecardPosterConfigure.setPosterType(posterType);
        List<EcardPosterConfigure> list = ecardPosterConfigureService.selectEcardPosterConfigureList(ecardPosterConfigure);
        return ResponseModel.ok(list);
    }

    /**
     * 获取自制海报图片列表，根据登陆用户ID查询
     *
     * @author yjs
     * @date 2022/12/6 10:30
     */
    @GetMapping("/getMyMakePosterList")
    @ApiOperation(value = "电子名片-海报-获取自制海报图片列表", notes = "电子名片-海报-获取自制海报图片列表")
    @ApiResponses({@ApiResponse(code = 0, message = "OK", response = EcardNewsConfig.class)})
    @ResponseBody
    public ResponseModel getMyMakePosterList() {
        String salt = getSalt();//盐值
        //获取当前用户的信息
        EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
        //法人机构信息
        SysDept secondLevelDept = deptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
        EcardPosterMakeList ecardPosterMakeList = new EcardPosterMakeList();
        ecardPosterMakeList.setUserId(userInfo.getUserId());
        ecardPosterMakeList.setDeptId(secondLevelDept.getDeptId());
        return ResponseModel.ok(ecardPosterMakeListService.selectEcardPosterMakeListList(ecardPosterMakeList));
    }

    /**
     * 获取我的海报（已生成海）报列表，根据登陆用户ID查询
     *
     * @author yjs
     * @date 2022/12/6 10:30
     */
    @GetMapping("/getMyGeneratedPosterList")
    @ApiOperation(value = "电子名片-海报-获取我的海报（已生成海）列表", notes = "电子名片-海报-获取我的海报（已生成海）列表")
    @ApiResponses({@ApiResponse(code = 0, message = "OK", response = EcardNewsConfig.class)})
    @ResponseBody
    public ResponseModel getMyGeneratedPosterList() {
        String salt = getSalt();//盐值
        //获取当前用户的信息
        EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
        //法人机构信息
        SysDept secondLevelDept = deptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
        EcardPosterShareList ecardPosterShareList = new EcardPosterShareList();
        ecardPosterShareList.setUserId(userInfo.getUserId());
        ecardPosterShareList.setDeptId(secondLevelDept.getDeptId());
        return ResponseModel.ok(ecardPosterShareListService.selectEcardPosterShareListList(ecardPosterShareList));
    }

    /**
     * 添加自制海报图片
     *
     * @author yjs
     * @date 2022/7/28 10:48
     */
    @PostMapping(value = "/addMyMakePoster")
    @ApiOperation(value = "电子名片-海报-添加自制海报图片", notes = "电子名片-海报-添加自制海报图片")
    @ResponseBody
    public ResponseModel addMyMakePoster(@RequestParam("imageFile") MultipartFile imageFile) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            //法人机构信息
            SysDept secondLevelDept = deptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            if (!imageFile.isEmpty()) {
                String filePath = XydtechBusiPlatConfig.getEcardFilePath() + "/" + userInfo.getDeptId() + "/posterImg";
                logger.info("文件路径========" + filePath);
                EcardPosterMakeList ecardPosterMakeList = new EcardPosterMakeList();
                // 上传并返回新文件名称
                //20230711 update 加入图片文件类型后缀判断
                ecardPosterMakeList.setImgFile(FileUploadUtils.uploadFileType(
                        filePath, imageFile, minioUpload, MimeTypeUtils.IMAGE_EXTENSION));
                ecardPosterMakeList.setUserId(userInfo.getUserId());
                ecardPosterMakeList.setDeptId(secondLevelDept.getDeptId());
                int updateCount = ecardPosterMakeListService.insertEcardPosterMakeList(ecardPosterMakeList);
                return updateCount > 0 ? ResponseModel.ok() : ResponseModel.error("添加失败！");
            } else {
                return ResponseModel.error("海报图片不能为空！");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("添加海报失败");
        }
    }

    /**
     * 添加海报生成记录
     *
     * @author yjs
     * @date 2022/7/28 10:48
     */
    @PostMapping(value = "/addPosterShare")
    @ApiOperation(value = "电子名片-海报-添加海报生成记录", notes = "电子名片-海报-添加海报生成记录")
    @ResponseBody
    public ResponseModel addPosterShare(EcardPosterShareList ecardPosterShareList, @RequestParam("imageFile") MultipartFile imageFile) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            //法人机构信息
            SysDept secondLevelDept = deptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            if (!imageFile.isEmpty()) {
                String filePath = XydtechBusiPlatConfig.getEcardFilePath() + "/" + userInfo.getDeptId() + "/posterImg";
                logger.info("文件路径========" + filePath);
                //20230711 update 加入图片文件类型后缀判断
                ecardPosterShareList.setImgFile(FileUploadUtils.uploadFileType(filePath, imageFile, minioUpload, MimeTypeUtils.IMAGE_EXTENSION));
                ecardPosterShareList.setUserId(userInfo.getUserId());
                ecardPosterShareList.setDeptId(secondLevelDept.getDeptId());
                int updateCount = ecardPosterShareListService.insertEcardPosterShareList(ecardPosterShareList);
                return updateCount > 0 ? ResponseModel.ok() : ResponseModel.error("添加失败！");
            } else {
                return ResponseModel.error("海报图片不能为空！");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("添加海报失败");
        }
    }

    /**
     * 根据自制海报ID删除自制海报
     *
     * @author yjs
     * @date 2022/12/6 10:30
     */
    @GetMapping("/delMyMakePoster")
    @ApiOperation(value = "电子名片-海报-获取自制海报", notes = "电子名片-海报-获取自制海报")
    @ApiResponses({@ApiResponse(code = 0, message = "OK", response = EcardNewsConfig.class)})
    @ResponseBody
    public ResponseModel delMyMakePoster(@RequestParam(required = false) Long posterId, @RequestParam(required = false) String imgUrl) {
        String filePath = imgUrl.replaceAll("/profile", XydtechBusiPlatConfig.getProfile());
        File file = new File(filePath);
        if (file.exists() && filePath.contains(XydtechBusiPlatConfig.getProfile())) { //如果文件存在,则删除数据
            file.delete();
        }
        return ResponseModel.ok(ecardPosterMakeListService.deleteEcardPosterMakeListById(posterId));
    }

    /**
     * 获取微信小程序二维码
     *
     * @author yjs
     * @date 2022/12/6 10:30
     */
    @GetMapping("/getWeChatQrCode")
    @ApiOperation(value = "电子名片-海报-获取微信小程序二维码", notes = "电子名片-海报-获取微信小程序二维码")
    @ApiResponses({@ApiResponse(code = 0, message = "OK", response = EcardNewsConfig.class)})
    @ResponseBody
    public ResponseModel getWeChatQrCode() {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            //法人机构信息
            SysDept secondLevelDept = deptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            SysWechatApplet wechatAppletByAppId = sysWeChatAppletService.getWechatAppletByDeptId(ApiContant.APPLETTYPE_ECARD, secondLevelDept.getDeptId());
            if (wechatAppletByAppId == null) {
                throw new ApiException(ResultStatus.APPLET_CONFIG_IS_MISSING);
            }
            //获取线上快贷小程序的access_token信息
            String accessToken = WechatTokenUtil.getEcardMiniProgramAccessToken(wechatAppletByAppId.getAppid(), wechatAppletByAppId.getSecret(), urlConfig.appleSendUrl, apiServiceUrl);
            String params = "registId=" + getCurrentUserId();
            GetWechatQRCodeResponse wechatQRCodeResponse = WeChatQrCodeUtil.getMiniProgramQRCodeToBigData(apiServiceUrl, accessToken, params);
            int code = wechatQRCodeResponse.getErrcode();
            if (code == 0) {
                return ResponseModel.ok("data:image/jpg;base64," + Base64.getEncoder().encodeToString(wechatQRCodeResponse.getBuffer()));
            } else {
                return ResponseModel.error(wechatQRCodeResponse.getErrmsg());
            }
        }catch (ApiException e){
            return ResponseModel.error("小程序相关配置缺失");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseModel.error("获取小程序二维码失败");
        }
    }

    /**
     * 获取海报分享个人信息记录，根据登陆用户ID查询
     *
     * @author yjs
     * @date 2022/12/6 10:30
     */
    @GetMapping("/getMyPrdDefinedSkip")
    @ApiOperation(value = "电子名片-海报-获取海报分享个人信息记录", notes = "电子名片-海报-获取海报分享个人信息记录")
    @ApiResponses({@ApiResponse(code = 0, message = "OK", response = EcardNewsConfig.class)})
    @ResponseBody
    public ResponseModel getMyPosterShareConf() {
        String salt = getSalt();//盐值
        //获取当前用户的信息
        EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
        //法人机构信息
        SysDept secondLevelDept = deptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
        EcardPosterShareConf ecardPosterShareConf = new EcardPosterShareConf();
        ecardPosterShareConf.setUserId(userInfo.getUserId());
        ecardPosterShareConf.setDeptId(secondLevelDept.getDeptId());
        //因为一个用户就只有条数据，所以直接取第一条返回
        List<EcardPosterShareConf> confList = ecardPosterShareConfService.selectEcardPosterShareConfList(ecardPosterShareConf);
        if (confList.size() > 0) {
            return ResponseModel.ok(confList.get(0));
        }
        return ResponseModel.ok();
    }

    /**
     * 保存海报分享个人信息记录
     *
     * @author yjs
     * @date 2022/7/28 10:48
     */
    @PostMapping(value = "/addPosterShareConf")
    @ApiOperation(value = "电子名片-海报-保存海报分享个人信息记录", notes = "电子名片-海报-保存海报分享个人信息记录")
    @ResponseBody
    public ResponseModel addPosterShareConf(EcardPosterShareConf ecardPosterShareConf, @RequestParam("imageFile") MultipartFile imageFile) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            //法人机构信息
            SysDept secondLevelDept = deptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            //原二维码路径,删除原二维码
            String oldQrCodeUrl = ecardPosterShareConf.getOldQrCodeUrl();
            if (oldQrCodeUrl != null && oldQrCodeUrl != "") {
                String filePath = oldQrCodeUrl.replaceAll("/profile", XydtechBusiPlatConfig.getProfile());
                File file = new File(filePath);
                if (file.exists() && filePath.contains(XydtechBusiPlatConfig.getProfile())) { //如果文件存在,则删除数据
                    file.delete();
                }
            }
            if (!imageFile.isEmpty()) {
                String filePath = XydtechBusiPlatConfig.getEcardFilePath() + "/" + userInfo.getDeptId() + "/poster/qrCodeImg";
                //20230711 update 加入图片文件类型后缀判断
                ecardPosterShareConf.setQrCodeUrl(FileUploadUtils.uploadFileType(filePath, imageFile, minioUpload, MimeTypeUtils.IMAGE_EXTENSION));
            }
            ecardPosterShareConf.setUserId(userInfo.getUserId());
            ecardPosterShareConf.setDeptId(secondLevelDept.getDeptId());
            int updateCount = ecardPosterShareConfService.addPosterShareConf(ecardPosterShareConf);
            return updateCount > 0 ? ResponseModel.ok() : ResponseModel.error("保存失败！");
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("保存失败，请联系管理员");
        }
    }

}
